package com.martin.lib_base.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.martin.lib_base.ktx.loge
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * 全局可调用的ViewModel
 */
open class GlobalViewModel : ViewModel() {
    // 消息数量
    var messageCount = MutableStateFlow(0)

    // 修改消息数量
    fun postMessageCount(count: Int) {
        messageCount.value = count
    }

    // 监听消息数量
    fun observeMessageCount(scope: CoroutineScope? = null, method: (Int) -> Unit = { _ -> }) {
        val mScope = scope ?: viewModelScope
        mScope.launch {
            messageCount.collect {
                loge("observeMessageCount count == $it")
                method.invoke(it)
            }
        }
    }
}